package com.fh.huanxin.controller;

import java.io.File;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fh.huanxin.HTTPClientUtils;
import com.fh.huanxin.com.Constants;
import com.fh.huanxin.com.HTTPMethod;
import com.fh.huanxin.com.Roles;
import com.fh.huanxin.vo.ClientSecretCredential;
import com.fh.huanxin.vo.Credential;
import com.fh.huanxin.vo.EndPoints;
import com.fh.util.DateUtil;
import com.fh.util.Logger;
import com.fh.util.PageData;

/**
 * 
 * @包名 :com.fh.huanxin.controller
 * @文件名 :HxmsgSend.java
 *      TODO 类作用：环信发送消息
 * @Author: 孙超文 386480250@qq.com
 * @Date: 2015-7-7 下午1:29:58
 */

public class HxmsgSend {
	protected static Logger logger = Logger.getLogger(HxmsgSend.class);
	private static final JsonNodeFactory factory = new JsonNodeFactory(false);
	private static final String APPKEY = Constants.APPKEY;
	// 通过app的client_id和client_secret来获取app管理员token
	private static Credential credential = new ClientSecretCredential(Constants.APP_CLIENT_ID,
			Constants.APP_CLIENT_SECRET, Roles.USER_ROLE_APPADMIN);

	public static void main(String[] args) {
		PageData pd = new PageData();
		pd.put("hxusername", "zhangsan");
		pd.put("hxpassword", "1");
		pd.put("targetTypeus", "users"); // users 给用户发消息, chatgroups 给群发消息
		pd.put("tohxuser", "scw_vip");
		pd.put("msg", DateUtil.getTime() + "我是来发消息的");
		// 登录
		Object userlog = HxmsgDasis.hxuserlog(pd);
		if (null != userlog) {
			System.out.println("登录" + userlog);
		}
		// 检查用户是否在线
		Object usernode = HxmsgDasis.hxuserstatus(pd);
		if (null != usernode) {
			System.out.println("是否在线" + usernode);

			// int k = 10;
			// for (int i = 0; i < k; i++) {
			//
			// }
			HxmsgSend.hxaudiomessages(pd);

		}
	}

	/**
	 * 
	 * TODO 方法作用：发送文本消息
	 * 
	 * @param pd
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午1:33:32
	 */
	public static Object hxtxtmessages(PageData pd) {
		// user 给好友消息 chatgroups 群消息
		// 给用户发一条文本消息
		// 给用户发一条文本消息
		String from = pd.getString("hxusername");
		String targetTypeus = pd.getString("targetTypeus");
		ObjectNode ext = factory.objectNode();
		ArrayNode targetusers = factory.arrayNode();
		targetusers.add(pd.getString("tohxuser"));
		ObjectNode txtmsg = factory.objectNode();
		txtmsg.put("msg", pd.getString("msg"));
		txtmsg.put("type", "txt");
		ObjectNode sendTxtMessageusernode = sendMessages(targetTypeus, targetusers, txtmsg, from, ext);
		if (null != sendTxtMessageusernode) {
			logger.info("给用户发一条文本消息: " + sendTxtMessageusernode.toString());
		}
		System.out.println(sendTxtMessageusernode);
		return sendTxtMessageusernode;
	}

	/**
	 * 
	 * TODO 方法作用：发送图片消息
	 * 
	 * @param pd
	 * @return
	 * @Author: 孙超文
	 * @Date: 2015-7-7 下午3:31:48
	 */
	public static Object hximgmessages(PageData pd) {
		String from = pd.getString("hxusername");
		String targetTypeus = pd.getString("targetTypeus");
		ObjectNode ext = factory.objectNode();
		ArrayNode targetusers = factory.arrayNode();
		targetusers.add(pd.getString("tohxuser"));

		File uploadImgFile = new File("D:/孙超文.jpg");
		String fileName = uploadImgFile.getName();
		ObjectNode imgDataNode = HxFiles.mediaUpload(uploadImgFile);
		if (null != imgDataNode) {
			String imgFileUUID = imgDataNode.path("entities").get(0).path("uuid").asText();
			String shareSecret = imgDataNode.path("entities").get(0).path("share-secret").asText();

			logger.info("上传图片文件: " + imgDataNode.toString());

			ObjectNode imgmsg = factory.objectNode();
			imgmsg.put("type", "img");
			imgmsg.put("url", HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatfiles/" + imgFileUUID)
					.toString());
			imgmsg.put("filename", fileName);
			imgmsg.put("length", 10);
			imgmsg.put("secret", shareSecret);
			ObjectNode sendimgMessageusernode = sendMessages(targetTypeus, targetusers, imgmsg, from, ext);
			if (null != sendimgMessageusernode) {
				logger.info("给一个群组发文本消息: " + sendimgMessageusernode.toString());
			}
			return sendimgMessageusernode;
		}
		return null;
	}

	public static Object hxaudiomessages(PageData pd) {

		String from = pd.getString("hxusername");
		String targetTypeus = pd.getString("targetTypeus");
		ObjectNode ext = factory.objectNode();
		ArrayNode targetusers = factory.arrayNode();
		targetusers.add(pd.getString("tohxuser"));

		File uploadAudioFile = new File("D:/凤凰传奇 - 全是爱.mp3");
		String fileName = uploadAudioFile.getName();
		ObjectNode audioDataNode = HxFiles.mediaUpload(uploadAudioFile);
		if (null != audioDataNode) {
			String audioFileUUID = audioDataNode.path("entities").get(0).path("uuid").asText();
			String audioFileShareSecret = audioDataNode.path("entities").get(0).path("share-secret").asText();
			logger.info("上传语音文件: " + audioDataNode.toString());
			ObjectNode audiomsg = factory.objectNode();
			audiomsg.put("type", "audio");
			audiomsg.put("url",
					HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatfiles/" + audioFileUUID)
							.toString());
			audiomsg.put("filename", fileName);
			audiomsg.put("length", 10);
			audiomsg.put("secret", audioFileShareSecret);
			ObjectNode sendaudioMessageusernode = sendMessages(targetTypeus, targetusers, audiomsg, from, ext);
			if (null != sendaudioMessageusernode) {
				logger.info("给用户发一条语音消息: " + sendaudioMessageusernode.toString());
			}
		}
		return null;
	}

	/**
	 * 发送消息
	 * 
	 * @param targetType
	 *            消息投递者类型：users 用户, chatgroups 群组
	 * @param target
	 *            接收者ID 必须是数组,数组元素为用户ID或者群组ID
	 * @param msg
	 *            消息内容
	 * @param from
	 *            发送者
	 * @param ext
	 *            扩展字段
	 * 
	 * @return 请求响应
	 */
	public static ObjectNode sendMessages(String targetType, ArrayNode target, ObjectNode msg, String from,
			ObjectNode ext) {

		ObjectNode objectNode = factory.objectNode();

		ObjectNode dataNode = factory.objectNode();

		// check appKey format
		if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
			logger.error("Bad format of Appkey: " + APPKEY);

			objectNode.put("message", "Bad format of Appkey");

			return objectNode;
		}

		// check properties that must be provided
		if (!("users".equals(targetType) || "chatgroups".equals(targetType))) {
			logger.error("TargetType must be users or chatgroups .");

			objectNode.put("message", "TargetType must be users or chatgroups .");

			return objectNode;
		}

		try {
			// 构造消息体
			dataNode.put("target_type", targetType);
			dataNode.put("target", target);
			dataNode.put("msg", msg);
			dataNode.put("from", from);
			dataNode.put("ext", ext);

			objectNode = HTTPClientUtils.sendHTTPRequest(EndPoints.MESSAGES_URL, credential, dataNode,
					HTTPMethod.METHOD_POST);

			objectNode = (ObjectNode) objectNode.get("data");
			for (int i = 0; i < target.size(); i++) {
				String resultStr = objectNode.path(target.path(i).asText()).asText();
				if ("success".equals(resultStr)) {
					logger.error(String.format("Message has been send to user[%s] successfully .", target.path(i)
							.asText()));
				} else if (!"success".equals(resultStr)) {
					logger.error(String.format("Message has been send to user[%s] failed .", target.path(i).asText()));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return objectNode;
	}

	/**
	 * "target_type" : "users", // users 给用户发消息, chatgroups 给群发消息
	 * "target" : ["u1", "u2", "u3"], // 注意这里需要用数组,数组长度建议不大于20, 即使只有一个用户,
	 * // 也要用数组 ['u1'], 给用户发送时数组元素是用户名,给群组发送时
	 * // 数组元素是groupid
	 * "msg" : {
	 * "type" : "txt",
	 * "msg" : "hello from rest" //消息内容，参考[聊天记录](http://www.easemob.com/docs/rest/chatmessage/)里的bodies内容
	 * },
	 * "from" : "jma2", //表示这个消息是谁发出来的, 可以没有这个属性, 那么就会显示是admin, 如果有的话, 则会显示是这个用户发出的
	 * "ext" : { //扩展属性, 由app自己定义.可以没有这个字段，但是如果有，值不能是“ext:null“这种形式，否则出错
	 * "attr1" : "v1",
	 * "attr2" : "v2"
	 */
}
